package com.mydemo.algorithm;

import java.util.HashMap;
import java.util.Map;

public class LengthOfLongestSubstring {
    public static void main(String[] args) {
        System.out.println(new LengthOfLongestSubstring().lengthOfLongestSubstring("abcabcbb"));
        System.out.println(new LengthOfLongestSubstring().lengthOfLongestSubstring("bbbbb"));
        System.out.println(new LengthOfLongestSubstring().lengthOfLongestSubstring("pwwkew"));
        System.out.println(new LengthOfLongestSubstring().lengthOfLongestSubstring("dvdf"));
        System.out.println(new LengthOfLongestSubstring().lengthOfLongestSubstring("abba"));
    }

    public int lengthOfLongestSubstring(String s) {
        if (s == null) {
            return 0;
        }
        // 字符和位置的对应关系
        Map<Character, Integer> charMap = new HashMap<>();
        int max = 0;
        int pre_point = 0;
        char[] chars = s.toCharArray();
        int size = chars.length;
        for (int i = 0; i < size; i++) {
            char v = chars[i];
            // 判断当前字符是否已存在
            Integer oldIndex = charMap.get(v);
            if (oldIndex != null && oldIndex >= pre_point){
                // 有重复当前记录当前的最大长度
                int curCount = i - pre_point;
                if (curCount > max){
                    max = curCount;
                }
                pre_point = oldIndex + 1;
            }
            charMap.put(v,i);
        }
        if (size - pre_point > max){
            max = size - pre_point;
        }
        return max;
    }
}
